import axios from 'axios';
import config from '../config.js'

import cookies from './cookies.js'

import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);

// const axios = axios.create()
axios.defaults.baseURL = config.apiBaseUrl // 3
axios.defaults.timeout = 60000
axios.defaults.headers.post['Content-Type'] = 'application/json'

// 添加请求拦截器
axios.interceptors.request.use(function(config) {
  config.headers['tk-token'] = cookies.getCookie('token')
  return config;
}, function(error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function(res) {
    // code 值 大于0,显示 错误信息
    if (res.data.code > 0) {
      Toast.fail(res.data.msg);
      res.data.data = 0
      return false;
    } else if (res.data.code == -1) {
      // 返回-1的时候,说明需要登录
      cookies.setCookie('token', '');
      this.$router.push({ path: '/login', query: { redirect: '/' } });
    } else {
      return res;
    }
  },
  function(error) {
    return Promise.reject(error);
  });

const post = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    axios.post(url, data).then((response) => {
      resolve(response.data)
    }).catch((response) => {
      resolve(response)
    })
  })
}
const get = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    axios.get(url, data).then((response) => {
      resolve(response.data)
    }, (response) => {
      reject(response)
    })
  })
}

export default {
  install(Vue) {
    Object.defineProperties(Vue.prototype, {
      apiGet: {
        value: get
      },
      apiPost: {
        value: post
      }
    })
  }
}
